﻿using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Windows;
namespace Helper
{
    public class ConstraintDefn
    {
        public ConstraintDefn()
        {
        }
        public ConstraintDefn(string name, string definition, string columnName)
        {
            Name = name;
            Definition = definition;
            ColumnName = columnName;
        }
        public string Name
        { get; set; }
        public string Definition
        { get; set; }
        public string ColumnName
        { get; set; }

    }

    public class ColumnDefn
    {
        public ColumnDefn(string columnName, string dataType, string isnullable, int maxlength)
        {
            ColumnName = columnName;
            DataType = dataType;
            IsNullable = isnullable;
            if (maxlength > 0)
                MaxLength = maxlength.ToString();
            else
                MaxLength = "MAX";
        }
        public ColumnDefn(string columnName)
        {
            ColumnName = columnName;
            DataType = "VARCHAR";
            IsNullable = "NOT NULL";
            MaxLength = "50";
        }
        public ColumnDefn()
        { }
        public string ColumnName
        {
            get;
            set;
        }

        public string DataType
        {
            get;
            set;
        }
        public string IsNullable
        {
            get;
            set;
        }
        public string MaxLength
        {
            get;
            set;
        }

        public string FullDataTypeName { get { return GetFullDataTypeName(); } }
        private string GetFullDataTypeName()
        {
            ObservableCollection<string> lengthOrientedDataTypes =
                new ObservableCollection<string>() { "binary", "char", "nchar", "nvarchar", "varbinary", "varchar" };
            bool isLenOrntd = false;
            foreach (string s in lengthOrientedDataTypes)
            {
                if (s.ToUpperInvariant() == DataType.ToUpperInvariant())
                {
                    isLenOrntd = true;
                    break;
                }
            }
            if (isLenOrntd)
                return DataType += "(" + MaxLength + ")";
            else
                return DataType;
        }
    }

    public class TableDefn
    {
        public TableDefn()
        {

        }
        public TableDefn(string nameOfTable)
        {
            Schema ="Users";
            NameOfTable = nameOfTable;
        }
        public TableDefn(string schema, string nameOfTable, string objectID, ObservableCollection<ColumnDefn> columnCollection,
            string primaryKey, ObservableCollection<ConstraintDefn> constraints)
        {
            Schema = schema;
            NameOfTable = nameOfTable;
            ObjectID = objectID;
            ColumnCollection = columnCollection;
            PrimaryKeyField = primaryKey;
            ConstraintCollection = constraints;
        }
        public TableDefn(string schema, string nameOfTable)
        {
            Schema = schema;
            NameOfTable = nameOfTable;
        }
        public string Schema
        {
            get;
            set;
        }
        public ObservableCollection<ConstraintDefn> ConstraintCollection
        {
            get;
            set;
        }
        public string PrimaryKeyField
        {
            get;
            set;
        }
        public string NameOfTable
        {
            get;
            set;
        }

        public ObservableCollection<ColumnDefn> ColumnCollection
        {
            get;
            set;
        }

        public string ObjectID { get; set; }
    }

    public class ObjectDefn
    {
        string createScript = "";
        public ObjectDefn()
        {

        }
        public ObjectDefn(string nameOfObject)
        {
            NameOfObject = nameOfObject;
        }
        public ObjectDefn(string schema, string nameOfObject, string objectID, DatabaseObjectTypes objectType,
            string createScript)
        {
            Schema = schema;
            NameOfObject = nameOfObject;
            ObjectID = objectID;
            ObjectType = objectType;
            CreateScript = createScript;
        }
        public string Schema
        {
            get;
            set;
        }
        public string NameOfObject
        {
            get;
            set;
        }
        public string ObjectID
        {
            get;
            set;
        }
        private void GenerateTrueScript()
        {
            createScript = createScript.Replace("'", "''");
            createScript = "EXEC " +Helper.Properties.Settings.Default.DBName + "..sp_executesql N'" + createScript + "'";
        }
        public string CreateScript
        {
            get { return createScript; }
            set { createScript = value; GenerateTrueScript(); }
        }
        public DatabaseObjectTypes ObjectType
        {
            get;
            set;
        }
    }

    public class DatabaseDefn
    {
        public DatabaseDefn()
        {
            TablesDefinition = new ObservableCollection<TableDefn>();
            ObjectsDefinition = new ObservableCollection<ObjectDefn>();
            SchemasDefinition = new ObservableCollection<string>();
            NameOfDatabase = "";
        }

        #region Serializing Stuff
        public void SerializeObject(string path)
        {
            if (String.IsNullOrWhiteSpace(path))
                path =Helper.Properties.Settings.Default.DBNewSchemaFilePath;
            try
            {
                System.Xml.Serialization.XmlSerializer serializer =
                new System.Xml.Serialization.XmlSerializer(typeof(DatabaseDefn));
                FileStream fs = new FileStream(path,
                  FileMode.Create, FileAccess.ReadWrite, FileShare.None);

                serializer.Serialize(fs, this);
                fs.Flush();

                fs.Close();
            }
            catch { }
        }

        public void SerializeObject()
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer =
                new System.Xml.Serialization.XmlSerializer(typeof(DatabaseDefn));
                FileStream fs = new FileStream(Helper.Properties.Settings.Default.DBDefaultDefnFilePath,
                  FileMode.Create, FileAccess.ReadWrite, FileShare.None);

                serializer.Serialize(fs, this);
                fs.Flush();

                fs.Close();
            }
            catch { throw new Exception("Serialization Failed."); }
        }

        public static void SerializeObject(string path, Type objectsType, object instanceOfObject)
        {
            if (String.IsNullOrWhiteSpace(path))
                path =Helper.Properties.Settings.Default.DBNewSchemaFilePath;
            try
            {
                System.Xml.Serialization.XmlSerializer serializer =
                new System.Xml.Serialization.XmlSerializer(objectsType);
                FileStream fs = new FileStream(path,
                  FileMode.Create, FileAccess.ReadWrite, FileShare.None);

                serializer.Serialize(fs, instanceOfObject);
                fs.Flush();

                fs.Close();
            }
            catch { }
        }
        public static DatabaseDefn DeSerializeObject(string filename)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(DatabaseDefn));



                FileStream fs = new FileStream(filename, FileMode.Open);

                DatabaseDefn po = (DatabaseDefn)serializer.Deserialize(fs);
                return po;
            }
            catch { return new DatabaseDefn(); }
        }
        public static DatabaseDefn DeSerializeObject(Stream newStream)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(DatabaseDefn));

                DatabaseDefn po = (DatabaseDefn)serializer.Deserialize(newStream);
                return po;
            }
            catch { return new DatabaseDefn(); }
        }
        public static DatabaseDefn DeSerializeObject(System.Xml.XmlReader xmlReader)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(DatabaseDefn));


                DatabaseDefn po = (DatabaseDefn)serializer.Deserialize(xmlReader);
                return po;
            }
            catch { return new DatabaseDefn(); }
        }
        public static object DeSerializeObject(System.Xml.XmlReader xmlReader, Type returntype)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(returntype);

                object po = Activator.CreateInstance(returntype);
                po = serializer.Deserialize(xmlReader);
                return po;
            }
            catch
            {
                object po = Activator.CreateInstance(returntype);
                return po;
            }
        }

        #endregion

        #region Properties
        public ObservableCollection<TableDefn> TablesDefinition
        {
            get;
            set;
        }
        public ObservableCollection<ObjectDefn> ObjectsDefinition
        {
            get;
            set;
        }
        public ObservableCollection<string> SchemasDefinition
        {
            get;
            set;
        }
        public string NameOfDatabase { get; set; }
        #endregion

        #region Methods
        internal static ObservableCollection<ColumnDefn> GetImportProductColumns()
        {
            ObservableCollection<ColumnDefn> cl = new ObservableCollection<ColumnDefn>();
            cl.Add(new ColumnDefn("NameOfProduct"));
            cl.Add(new ColumnDefn("ProductCategory"));
            cl.Add(new ColumnDefn("NameOfVendor"));
            cl.Add(new ColumnDefn("SellingPrice"));
            cl.Add(new ColumnDefn("BuyingPrice"));
            cl.Add(new ColumnDefn("StartQuantity"));
            cl.Add(new ColumnDefn("CurrentQuantity"));
            return cl;
        }
        private static ObservableCollection<ColumnDefn> GetNonDefaultColumnsInTable(string tableNameWithoutSchema)
        {
            ObservableCollection<ColumnDefn> tempCls = new ObservableCollection<ColumnDefn>();
            ObservableCollection<ColumnDefn> temp1 = GetColumnsInTable(tableNameWithoutSchema);
            ObservableCollection<string> temp2 = new ObservableCollection<string>() { "DateAdded", "rowguid", "ModifiedDate" };
            bool isdefualtColl = false;
            foreach (ColumnDefn s in temp1)
            {
                isdefualtColl = false;
                foreach (string s2 in temp2)
                {
                    if (s.ColumnName.ToUpper() == s2.ToUpper())
                    {
                        isdefualtColl = true;
                        break;
                    }
                }
                if (!isdefualtColl)
                    tempCls.Add(s);
            }
            return tempCls;
        }


        private static ObservableCollection<string> GetAllTableNames()
        {
            string selectStr = "SELECT name FROM sys.objects WHERE type = 'U'";
            return DataAccessHelper.CopyFromDBtoObservableCollection(selectStr);
        }
        internal static ObservableCollection<string> GetColumnNamesInTable(string tableNameWithoutSchema)
        {
            ObservableCollection<string> temp = new ObservableCollection<string>();
            ObservableCollection<ColumnDefn> obs = DatabaseDefn.GetColumnsInTable(tableNameWithoutSchema);
            foreach (ColumnDefn c in obs)
            {
                temp.Add(c.ColumnName);
            }
            return temp;
        }
        private static ObservableCollection<ColumnDefn> GetColumnsInTable(string tableNameWithoutSchema)
        {
            string selectStr =
             "SELECT C.name AS ColumnName, P.name AS DataType,CASE c.is_nullable " +
             "WHEN 1 THEN 'NULL' ELSE 'NOT NULL' END AS IsNullable,c.max_length as MaxLength " +
"FROM SYS.OBJECTS AS T   JOIN SYS.COLUMNS AS C ON T.OBJECT_ID = C.OBJECT_ID JOIN " +
"SYS.TYPES AS P ON C.SYSTEM_TYPE_ID = P.SYSTEM_TYPE_ID " +
"WHERE T.TYPE_DESC = 'USER_TABLE' AND T.name='" + tableNameWithoutSchema + "' ORDER BY c.column_id";

            DataTable dt = DataAccessHelper.ExecuteNonQueryWithResultTable(selectStr);
            ObservableCollection<ColumnDefn> cols = new ObservableCollection<ColumnDefn>();
            foreach (DataRow dtr in dt.Rows)
            {
                cols.Add(new ColumnDefn(dtr[0].ToString(), dtr[1].ToString(), dtr[2].ToString(),
                    Int32.Parse(dtr[3].ToString())));
            }
            return cols;
        }
        internal static string GetTablePrimaryKey(string tableNameWithoutSchema, string schemaName)
        {
            string selectStr =
" exec sp_pkeys '" + tableNameWithoutSchema + "' ,'" + schemaName + "'";
            try
            {
                DataTable tbl = DataAccessHelper.ExecuteNonQueryWithResultTable(selectStr);
                if ((tbl != null) && (tbl.Rows != null) && (tbl.Rows.Count > 0))
                    return tbl.Rows[0][3].ToString();
            }
            catch { }
            return "";
        }


        private static ObservableCollection<string> GetTableColumns(string nameOfTable)
        {
            string selectStr = "SELECT COLUMN_NAME FROM " +Helper.Properties.Settings.Default.DBName + ".INFORMATION_SCHEMA.COLUMNS WHERE UPPER(TABLE_NAME) = '" + nameOfTable.ToUpper() +
            "' AND UPPER(COLUMN_NAME) NOT IN (UPPER('rowguid'),UPPER('ModifiedDate'))";
            return DataAccessHelper.CopyFromDBtoObservableCollection(selectStr);
        }

        public static bool RecreateDatabase(DatabaseDefn ds)
        {
            string createStr = DatabaseScript.GetDBCreateScript(ds.NameOfDatabase);
            string dropStr = DatabaseScript.GetDropScript(ds.NameOfDatabase);
            bool succ = true;
            try
            {

                if (CheckDB())
                {
                    succ = succ&&DataAccessHelper.ExecuteNonQuery(dropStr, false);
                }

                succ = succ &&
                    DataAccessHelper.ExecuteNonQuery(createStr, false);
                createStr = DatabaseScript.GetSchemasScript(ds.SchemasDefinition);
               succ = succ&&
                    DataAccessHelper.ExecuteNonQuery(createStr, false);
                createStr = DatabaseScript.GetTablesScript(ds.TablesDefinition);
               succ = succ&&
                    DataAccessHelper.ExecuteNonQuery(createStr, false);
                createStr = DatabaseScript.GetObjectsScript(ds.ObjectsDefinition);
               succ = succ&&
                    DataAccessHelper.ExecuteNonQuery(createStr, false);
            }
            catch { }
            return succ;
        }

        internal static ObservableCollection<ConstraintDefn> GetTableConstraints(string tableNameWithoutSchema, string schemaName)
        {
            if ((string.IsNullOrWhiteSpace(tableNameWithoutSchema)) || (string.IsNullOrWhiteSpace(schemaName)))
                return new ObservableCollection<ConstraintDefn>();
            string selectStr = "SELECT d.name, d.definition,c.name FROM sys.default_constraints d left outer join sys.columns c " +
"on(d.parent_object_id=c.object_id and d.parent_column_id=c.column_id) " +
"where d.parent_object_id =  OBJECT_ID(N'" + schemaName + "." + tableNameWithoutSchema + "', N'U')";

            DataTable dt = DataAccessHelper.ExecuteNonQueryWithResultTable(selectStr);
            ObservableCollection<ConstraintDefn> constraints = new ObservableCollection<ConstraintDefn>();
            foreach (DataRow r in dt.Rows)
            {
                constraints.Add(new ConstraintDefn(r[0] as string, r[1] as string, r[2] as string));
            }

            return constraints;
        }
        private static ObservableCollection<TableDefn> GetDatabaseTablesFromDb(string nameOfDB)
        {
            ObservableCollection<TableDefn> tables = new ObservableCollection<TableDefn>();
           
            try
            {
                string selectStr = "USE " + nameOfDB + " select object_schema_name(object_id),name, object_id from sys.tables";

                DataTable result = DataAccessHelper.ExecuteNonQueryWithResultTable(selectStr, false);

                        foreach (DataRow dtr in result.Rows)
                        {
                            tables.Add(new TableDefn(dtr[0] as string, dtr[1] as string, dtr[2] as string,
                                GetColumnsInTable(dtr[1] as string),
                                GetTablePrimaryKey(dtr[1] as string, dtr[0] as string),
                                GetTableConstraints(dtr[1] as string,  dtr[0] as string)
                                ));
                        }
                    
            }
            catch { }
            return tables;
        }
        private static ObservableCollection<TableDefn> GetDatabaseTablesFromDb()
        {
            return GetDatabaseTablesFromDb(Helper.Properties.Settings.Default.DBName);
        }



        public static DatabaseDefn GetCurrentDBDefn(string nameOfDB)
        {
            DatabaseDefn tempCls = new DatabaseDefn();
            tempCls.NameOfDatabase = nameOfDB;
            tempCls.TablesDefinition = GetDatabaseTablesFromDb(nameOfDB);
            tempCls.ObjectsDefinition = GetDatabaseObjectsFromDb(nameOfDB);
            tempCls.SchemasDefinition = GetDatabaseSchemasFromDb(nameOfDB);
            return tempCls;
        }
        public static DatabaseDefn GetCurrentDBDefn()
        {
            return GetCurrentDBDefn(Helper.Properties.Settings.Default.DBName);
        }

        private static ObservableCollection<string> GetDatabaseSchemasFromDb(string nameOfDB)
        {
            ObservableCollection<string> tempColl = new ObservableCollection<string>();
            string selectStr = "use " + nameOfDB + "\r\nselect * from sys.schemas where principal_id = 1 and name<>'dbo'";
            DataTable sDt = DataAccessHelper.ExecuteNonQueryWithResultTable(selectStr, false);

            foreach (DataRow dtr1 in sDt.Rows)
            {
                tempColl.Add(dtr1[0] as string);
            }
            return tempColl;
        }
        private static ObservableCollection<ObjectDefn> GetDatabaseObjectsFromDb(string nameOfDB)
        {
            ObservableCollection<ObjectDefn> tempColl = new ObservableCollection<ObjectDefn>();
            string fnSelectStr = "use " + nameOfDB + "\r\nselect object_schema_name(object_id), object_name(object_id), " +
                "object_id,object_definition(object_id) from sys.objects where (type = 'FN' or type='IF' or type='TF') " +
                "order by type desc";
            string spSelectStr = "use " + nameOfDB + "\r\nselect object_schema_name(object_id), name, object_id,object_definition(object_id) from sys.Procedures";
            DataTable fnDt = DataAccessHelper.ExecuteNonQueryWithResultTable(fnSelectStr, false);
            DataTable spDt = DataAccessHelper.ExecuteNonQueryWithResultTable(spSelectStr, false);

            foreach (DataRow dtr1 in fnDt.Rows)
            {
                tempColl.Add(new ObjectDefn(dtr1[0] as string,
                    dtr1[1] as string, dtr1[2] as string, DatabaseObjectTypes.Function, dtr1[3] as string));
            }

            foreach (DataRow dtr2 in spDt.Rows)
            {
                tempColl.Add(new ObjectDefn( dtr2[0] as string,
                    dtr2[1] as string, dtr2[2] as string, DatabaseObjectTypes.Procedure, dtr2[3] as string));
            }
            return tempColl;
        }
        private static ObservableCollection<ObjectDefn> GetDatabaseObjectsFromDb()
        {
            return GetDatabaseObjectsFromDb(Helper.Properties.Settings.Default.DBName);
        }
        public static DatabaseDefn GetDefaultDBDefn()
        {
            DatabaseDefn d = new DatabaseDefn();
            try
            {
                System.Windows.Resources.StreamResourceInfo s = System.Windows.Application.GetResourceStream(
                new Uri("pack://application:,,,/Resources/DbDefn.xml"));
                System.Xml.XmlReader dx = System.Xml.XmlReader.Create(s.Stream);

                d = DatabaseDefn.DeSerializeObject(dx);
            }
            catch { }
            return d;
        }
        #endregion


        public static void UpgradeDatabase(DatabaseDefn currentDefn, DatabaseDefn newDefn)
        {
            UpgradeObjects(currentDefn, newDefn);
            UpgradeSchemas(currentDefn, newDefn);
            UpgradeTables(currentDefn, newDefn);
        }

        private static void UpgradeTables(DatabaseDefn currentDefn, DatabaseDefn newDefn)
        {
            ObservableCollection<TableDefn> newTables = new ObservableCollection<TableDefn>();
            foreach (TableDefn newTd in newDefn.TablesDefinition)
            {
                bool exists = false;
                foreach (TableDefn oldTd in currentDefn.TablesDefinition)
                {
                    if (newTd.NameOfTable.ToUpperInvariant() == oldTd.NameOfTable.ToUpperInvariant())
                    {
                        exists = true;
                        ObservableCollection<ColumnDefn> newColumns = new ObservableCollection<ColumnDefn>();
                        foreach (ColumnDefn colNew in newTd.ColumnCollection)
                        {
                            bool colExists = false;
                            foreach (ColumnDefn colOld in oldTd.ColumnCollection)
                            {
                                if (colNew.ColumnName.ToUpperInvariant() == colOld.ColumnName.ToUpperInvariant())
                                    colExists = true;
                            }
                            if (!colExists)
                                newColumns.Add(colNew);
                        }
                        if (newColumns.Count > 0)
                        {
                            string alterStr = DatabaseScript.GetTablesAlterScript(oldTd, newTd);

                            DataAccessHelper.ExecuteNonQuery(alterStr, true);
                        }
                    }
                }
                if (!exists)
                    newTables.Add(newTd);
            }
            if (newTables.Count > 0)
            {
                string createStr = DatabaseScript.GetTablesScript(newTables);
                RegistryHelper.StoreTemp(createStr);
                MessageBox.Show(createStr);
                DataAccessHelper.ExecuteNonQuery(createStr, true);
            }



            foreach (TableDefn newTd in newDefn.TablesDefinition)
            {
                foreach (TableDefn oldTd in currentDefn.TablesDefinition)
                {
                    if (newTd.NameOfTable.ToUpperInvariant() == oldTd.NameOfTable.ToUpperInvariant())
                    {
                        ObservableCollection<ColumnDefn> newColumns = new ObservableCollection<ColumnDefn>();
                        foreach (ColumnDefn colNew in newTd.ColumnCollection)
                        {
                            bool colExists = false;
                            foreach (ColumnDefn colOld in oldTd.ColumnCollection)
                            {
                                if (colNew.ColumnName.ToUpperInvariant() == colOld.ColumnName.ToUpperInvariant())
                                    colExists = true;
                            }
                            if (!colExists)
                                newColumns.Add(colNew);
                        }
                        if (newColumns.Count > 0)
                        {
                            string alterStr = DatabaseScript.GetTablesAlterScript(oldTd, newTd);
                            RegistryHelper.StoreTemp(alterStr);
                            DataAccessHelper.ExecuteNonQuery(alterStr, true);
                        }
                    }
                }
            }

        }

        private static void UpgradeSchemas(DatabaseDefn currentDefn, DatabaseDefn newDefn)
        {
            ObservableCollection<string> newSchemas = new ObservableCollection<string>();
            foreach (string sc in newDefn.SchemasDefinition)
            {
                bool exists = false;
                foreach (string bt in currentDefn.SchemasDefinition)
                {
                    if (sc.ToUpperInvariant() == bt.ToUpperInvariant())
                        exists = true;
                }
                if (!exists)
                    newSchemas.Add(sc);
            }
            if (newSchemas.Count > 0)
            {
                string createStr = DatabaseScript.GetSchemasScript(newSchemas);
                DataAccessHelper.ExecuteNonQuery(createStr, true);
            }

        }

        private static void UpgradeObjects(DatabaseDefn currDefn, DatabaseDefn newDefn)
        {
            string dropStr = "USE " + currDefn.NameOfDatabase + "\r\n";
            foreach (ObjectDefn ob in currDefn.ObjectsDefinition)
            {
                dropStr += "if exists (select UPPER(name) from sys.objects where name='" + ob.NameOfObject.ToUpperInvariant() + "')\r\nDROP " + ob.ObjectType + " " + ob.NameOfObject + "\r\n";
            }
            DataAccessHelper.ExecuteNonQuery(dropStr, true);

            string createStr = DatabaseScript.GetObjectsScript(newDefn.ObjectsDefinition);
            DataAccessHelper.ExecuteNonQuery(createStr, true);
        }

        public static bool CheckSQLInstalled()
        {
            bool isOk1 = false;
            bool isOk2 = false;
            RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
            if (Environment.Is64BitOperatingSystem)
            {
                using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
                {
                    RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                    if (instanceKey != null)
                    {
                        foreach (var instanceName in instanceKey.GetValueNames())
                        {                           
                            isOk2 = true;
                            break;
                        }
                    }
                }
            }
            using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
            {
                RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                if (instanceKey != null)
                {
                    foreach (var instanceName in instanceKey.GetValueNames())
                    {
                        isOk1 = true;
                        break;
                    }
                }
            }
            return isOk1 || isOk2;
        }

        public static bool CheckInstanceInstalled()
        {
            bool isOk1 = false;
            bool isOk2 = false;
            RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
            if (Environment.Is64BitOperatingSystem)
            {
                using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
                {
                    RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                    if (instanceKey != null)
                    {
                        foreach (string instanceName in instanceKey.GetValueNames())
                        {
                            if (instanceName.ToUpperInvariant() == "STAREHE")
                            {
                                isOk2 = true;
                                break;
                            }
                        }
                    }
                }
            }
            using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
            {
                RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                if (instanceKey != null)
                {
                    foreach (var instanceName in instanceKey.GetValueNames())
                    {
                        if (instanceName.ToUpperInvariant() == "STAREHE")
                        {
                            isOk1 = true;
                            break;
                        }
                    }
                }
            }
            return isOk1 || isOk2;
        }

        public static bool CheckDefaultLogin()
        {
            try
            {
                string selectCtr = "USE [MASTER]";
                string custResults = DataAccessHelper.ExecuteScalar(selectCtr);
                    return true;
            }
            catch
            {
                return false;
            }            
        }

        public static bool CheckDB()
        {
            try
            {
                string selectCtr = "select name from sys.databases where UPPER(name)='" +
                   Helper.Properties.Settings.Default.DBName + "'";
                string custResults = DataAccessHelper.ExecuteScalar(selectCtr, false);

                if (string.IsNullOrWhiteSpace(custResults))               
                    return false;
               
                return true;
            }
            catch
            {
                return false;
            }
        }

        public static bool CheckDBObjects()
        {
            return true;
        }

       
    }
}